const DataLoader = require('dataloader')
import { Progress } from '../../models'
import { groupData, placeData } from '../../lib/graphql'
import fdb from '../../lib/fdb'
export const progressLoader = () =>
  new DataLoader(
    async keys => {
      let data = await Progress.findAll({ where: { id: { $in: keys } } })
      return placeData(keys, data, 'id')
    },
    { cacheKeyFn: key => key.toString() }
  )

export const progressLoaderByTask = () =>
  new DataLoader(
    async keys => {
      const data = await Progress.findAll({
        where: { taskId: { $in: keys } },
        order: [['createdAt', 'DESC']]
      })

      return groupData(keys, data, 'taskId')
    },
    { cacheKeyFn: key => key.toString() }
  )

export const memberLoader = () =>
  new DataLoader(
    async keys => {
      if (keys.length <= 0) return []
      let groupId = parseInt(keys[0].split('_')[0])
      let userIds = keys.map(n => {
        let t = n.split('_')
        return parseInt(t[1])
      })
      let members = await fdb.findAll({
        tbl: 'user_group as ug',
        joins: [
          'left join users as u on u.id = ug.userId'
        ],
        attrs: [
          'ug.*, u.nickName, u.avatarUrl, u.gender'
        ],
        where: [
          `ug.groupId=${groupId}`,
          `ug.userId in (${userIds.join(',')})`
        ],
        orders: [
          `createdAt desc`
        ]
      })
      return members
    },
    { cacheKeyFn: key => key.toString() }
  )
